package com.apes.autoparts.supplier.todo;

import com.apes.autoparts.supplier.platform.SupplierPlatform;
import com.apes.autoparts.supplier.platform.SupplierPlatformItem;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.MapUtil;
import com.apestech.framework.util.StringUtil;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/***
 * 供应商待办列表
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SupplierPlatformTodo.CONST_TABLE_NAME)
public class SupplierPlatformTodo extends Model {

    public static final String CONST_TABLE_NAME = "supplier_platform_todo";


    @Id
    @Comment("流水码")
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "供应商数据解析待办", prefix = "1", padding = 8)
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_platform_item_id", referencedColumnName = "id")
    @Comment("平台明细流水码")
    private SupplierPlatformItem supplierPlatformItem; //供应商

    @Comment("内部识别码")
    @Column(name = "source")
    private String source;

    @Comment("旧品牌")
    @Column(name = "old_brand_name")
    private String oldBrandName;

    @Comment("新品牌")
    @Column(name = "brand_name")
    private String brandName;

    @Column(name = "old_origin_place", length = 100)
    @Comment("旧产地")
    private String oldOriginPlace;  //产地

    @Column(name = "origin_place", length = 100)
    @Comment("新产地")
    private String originPlace;  //产地

    @Comment("旧零件编码")
    @Column(name = "old_part_code")
    private String oldPartCode;

    @Comment("新零件编码")
    @Column(name = "part_code")
    private String partCode;

    @Comment("旧零件名称")
    @Column(name = "old_part_code_name")
    private String oldPartCodeName;

    @Comment("新零件名称")
    @Column(name = "part_code_name")
    private String partCodeName;

    @Comment("旧单位")
    @Column(name = "old_unit")
    private String oldUnit;

    @Comment("新单位")
    @Column(name = "unit")
    private String unit;

    @Comment("备注")
    @Column(name = "remark")
    private String remark;

    @Comment("批次号")
    @Column(name = "batch")
    private String batch;

    @Comment("库存数量")
    @Column(name = "stock_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    private double stockQty = 0; // 库存数量

    @Comment("不含税金额")
    @Column(name = "untax_price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double untaxPrice = 0;

    @States(name = "状态", values = {
            @State(id = "waitingResolve", name = "待处理"),
            @State(id = "waitingConfirm", name = "待确认"),
            @State(id = "confirm", name = "已确认"),
    })
    @Comment("状态")
    private String state;

    @Transient
    private Map stateName;

    public Map getStateName() {
        if (this.state == null) return null;
        switch (this.state) {
            case "waitingResolve":
                return MapUtil.mapper(
                        "id", "waitingResolve",
                        "name", "待处理"
                );
            case "waitingConfirm":
                return MapUtil.mapper(
                        "id", "waitingConfirm",
                        "name", "待确认"
                );
            default:
                return MapUtil.mapper(
                        "id", "confirm",
                        "name", "已确认"
                );
        }
    }

    @States(name = "待办属性", values = {
            @State(id = "create", name = "新增"),
            @State(id = "update", name = "修改"),
            @State(id = "delete", name = "删除")
    })
    @Comment("待办属性")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "property", nullable = false, referencedColumnName = "id")
    private BusinessAttributeValue property;

    @Comment("处理人")
    @Column(name = "resolve_id", length = 4000)
    private String resolveId;


    @Comment("处理日期")
    @Column(name = "resolve_date")
    private Date resolveDate;

    @Comment("确认人")
    @Column(name = "confirm_id", length = 4000)
    private String confirmId;

    @Comment("确认日期")
    @Column(name = "confirm_date")
    private Date confirmDate;


    @OneToOne(mappedBy = "todo", cascade = CascadeType.ALL, orphanRemoval = true)
    private SupplierPlatformTodoParse todoParse;

    public SupplierPlatformTodoParse getTodoParse() {
        if (todoParse != null) {
            todoParse.setTodo(this);
        }
        return todoParse;
    }


    @Transient
    private Map supplier;

    public Map getSupplier() {
        if (supplierPlatformItem == null) return null;
        return supplierPlatformItem.getSupplierMap();
    }

    @Transient
    private SupplierPlatform supplierPlatform;

    public SupplierPlatform getSupplierPlatform() {
        if (supplierPlatformItem == null) return null;
        return supplierPlatformItem.getSupplierPlatform();
    }

    @Transient
    private Map resolves;  // 处理人
    public Map getResolves() {
        if (isWrite() || isLoad()) {
            resolves = StringToResolves(this.resolveId);
        }
        return resolves;
    }
    public void setResolves(Map map) {
        this.resolves = map;
        if (!isWrite()) {
            this.resolveId = resolvesToString(this.resolves);
        }
    }

    @Transient
    private Map confirms;
    public Map getConfirms() {
        if (isWrite() || isLoad()) {
            confirms = StringToResolves(this.confirmId);
        }
        return confirms;
    }
    public void setConfirms(Map map) {
        this.confirms = map;
        if (!isWrite()) {
            this.confirmId = resolvesToString(this.confirms);
        }
    }
    @Transient
    public Map StringToResolves(String st) {
        Map map = new HashMap();
        if (StringUtil.isEmpty(st)) return null;
        String[] rows = st.split(";");
        for (String row : rows) {
            if (row.contains(",")) {
                map.put(StringUtils.split(row, ",")[0], StringUtils.split(row, ",")[1]);
            }
        }
        return map;
    }

    public String resolvesToString(Map map) {
        StringBuffer sb = new StringBuffer();
        Set set = map.keySet();
        for (Object key : set) {
            sb.append(key.toString());
            sb.append(",");
            sb.append(map.get(key.toString()));
            sb.append(";");
        }
        return sb.toString();
    }
}
